package com.saianfu.common.security;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密
 */
public class MD5 {
    /**
     * 字符串MD5编码
     *
     * @param str 编码的字符串
     * @return  字符串MD5编码
     */
    public static String md5(String str) {
        Charset charset = Charset.forName("utf-8");

        return getString(str.getBytes(charset));
    }

    public static byte[] md5Bytes(String str) {
        Charset charset = Charset.forName("utf-8");
        return getByteArray(str.getBytes(charset));
    }

    private static byte[] getByteArray(byte[] bytes) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return md5.digest(bytes);
    }

    private static String getString(byte[] bytes) {
        byte[] md5Bytes = getByteArray(bytes);
        if (md5Bytes != null) {
            BigInteger b = new BigInteger(1, md5Bytes);
            return b.toString(16);
        } else {
            return null;
        }
    }

    /**
     * 字符串MD5编码
     * @param  bytes 字节数组
     * @return  字符串MD5编码
     */
    public static String md5(byte[] bytes) {
        return getString(bytes);
    }

}
